<template>
  <a-form-model
    ref="formComp"
    :model="formData"
    :rules="rules"
    layout="horizontal"
    style="padding: 20px 25px 10px 40px"
    class="AsteriskAfter editTestFormBox h100 newEditStyle rightDrawerWithoutCol "
  >
    <!-- 表单填写的基本信息 -->
    <!-- 基础配置 -->
    <fieldset>
      <legend>任务配置</legend>
      <a-row :gutter="40">
        <!-- 任务名称 -->
        <a-col :md="6" :sm="24">
          <a-form-model-item prop="name">
            <template #label>
              <span>{{ $t('campaignName') }}</span>
              <question-mark-tip
                :tip-title="'默认命名规则：测试类型_车型代码_智驾域测试版本号_日期时分秒'"
                :popupContainer="getPopupContainer">
              </question-mark-tip>
            </template>
            <a-input v-model="formData.name" />
          </a-form-model-item>
        </a-col>
        <!-- 车型代码 -->
        <a-col :md="6" :sm="24">
          <a-form-model-item :label="$t('modelCode')" prop="modelId">
            <car-model-select
              mode="default"
              :query="{ time }"
              :has-all="false"
              :default-value="formData.modelId"
              :clear="true"
              placeholder="请输入车型代码"
              @changeoption="changeModelBefore"
            ></car-model-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="40">
        <!-- 升级类型 -->
        <a-col :md="6" :sm="24">
          <!-- prop="type" -->
          <a-form-model-item>
            <template #label>
              <span>{{ $t('upgradeType') }}</span>
              <span class="requiredStar">*</span>
            </template>
            <a-radio-group
              v-model="upgradeTriggerType"
              @change="()=>{
                formData.circleStrategyId=undefined;
                formData.silenceUpgrade=undefined;
                formData.forceUpgrade=undefined}">
              <a-radio :key="9" value="USER">{{$t('usersj')}}
                <question-mark-tip :tip-title="$t('testUserTaskUpgradeTypeTip')" :popupContainer="getPopupContainer">
              </question-mark-tip></a-radio>
              <a-radio :key="8" value="AUTO">{{$t('zdsj')}}
                <question-mark-tip :tip-title="$t('testAutoTaskUpgradeTypeTip')" :popupContainer="getPopupContainer">
              </question-mark-tip>
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
        </a-col>
        <a-col :md="6" :sm="24">
          <!-- 强制升级 -->
          <a-form-model-item
            prop="forceUpgrade"
            key="forceUpgrade"
            v-if="upgradeTriggerType === 'USER'"
          >
            <template #label>
              <span>{{ $t('isQzsj') }}</span>
              <question-mark-tip :tip-title="$t('forceUpgradeTip')" :popupContainer="getPopupContainer">
              </question-mark-tip>
            </template>
            <a-radio-group v-model="formData.forceUpgrade" >
              <a-radio
                v-for="(item,index) in forceUpgradeType"
                :key="index"
                :value="item.value"
              >
                {{ $t(item.name) }}
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <!-- 静默升级 -->
          <a-form-model-item
            key="silenceUpgrade"
            v-else
            prop="silenceUpgrade"
          >
            <template #label>
              <span>{{ $t('sfjmsj') }}</span>
              <question-mark-tip :tip-title="$t('silenceUpgradeTip')" :popupContainer="getPopupContainer">
              </question-mark-tip>
            </template>
            <a-radio-group v-model="formData.silenceUpgrade">
              <a-radio
                v-for="(item,index) in slienceUpgradeType"
                :key="index"
                :value="item.value"
              >
                {{ $t(item.name) }}
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
        </a-col>
        <a-col :md="6" :sm="24">
          <!-- ECU升级类型 -->
          <a-form-model-item
            prop="ecuUpdateType"
          >
            <template #label>
              <span>{{ $t('ECU升级类型') }}</span>
              <question-mark-tip
                :tip-title="'请根据实际测试需求选择升级类型！注意：自由烧写不校验软件升级的适配性，容易误刷软件，请谨慎使用。'"
                :popupContainer="getPopupContainer">
              </question-mark-tip>
            </template>
            <a-radio-group v-model="formData.ecuUpdateType" :disabled="true">
              <!-- @change="changeEcuUpdateType" -->
              <a-radio key="2" :value="2">{{ $t('平刷') }}</a-radio>
              <a-radio key="4" :value="4" >{{ $t('循环升级') }}</a-radio>
            </a-radio-group>
          </a-form-model-item>
        </a-col>
      </a-row>
    </fieldset>
    <!-- 压测测试 -->
    <fieldset style="margin-top:10px">
      <legend>压测策略</legend>
      <a-row :gutter="40">
        <!-- 循环次数 -->
        <a-col :md="6" :sm="24">
          <a-form-model-item label="循环次数" prop="loopCount">
            <a-input-number :min="1" v-model="formData.loopCount" style="width:100%"/>
          </a-form-model-item>
        </a-col>
        <!-- 预约升级时间 -->
        <a-col :md="8" :sm="24">
          <!-- prop="bookingUpgradeTime" -->
          <a-form-model-item :label="$t('预约升级时间')" prop="bookingUpgradeTime">
            <a-range-picker
              v-model="formData.bookingUpgradeTime"
              :disabled-date="disabledDate"
              :disabledTime="disabledEndTime"
              :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
              @change="changeTime"
              @ok="confirmDates"
              format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
              :placeholder="['开始时间','结束时间']"/>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="40">
        <a-col :md="6" :sm="24">
          <!-- 任务终止条件 -->
          <a-form-model-item
          >
            <template #label>
              <span>任务终止条件(任意条件发生时)</span>
              <question-mark-tip
                :tip-title="'任意被选择的条件发生时终止任务'"
                :popupContainer="getPopupContainer">
              </question-mark-tip>
              <span class="requiredStar">*</span>
            </template>
            <a-checkbox
              @change="checkUpgradeFailed=$event.target.checked"
              :checked="true"
            >升级失败
            </a-checkbox>
          </a-form-model-item>
        </a-col>
        <a-col :md="6" :sm="24">
          <!-- 任务推送报告 -->
          <a-form-model-item
          >
            <template #label>
              <span>任务推送报告</span>
              <question-mark-tip
                :tip-title="'任务异常（差分失败，预约时间过，车辆归属变更）、任务完成（任务失败，任务结束）等结果通过邮件或企业微信推送'"
                :popupContainer="getPopupContainer">
              </question-mark-tip>
            </template>
            <a-checkbox
              @change="checkCreatedBy=$event.target.checked"
              :checked="checkCreatedBy"
              :disabled="true"
            >创建人
            </a-checkbox>
          </a-form-model-item>
        </a-col>
      </a-row>
    </fieldset>
    <!-- 条件策略 -->
    <fieldset style="margin-top:10px">
      <legend>条件策略</legend>
      <TestStrategy :time="nowTime" :id="conditionStrategyId" ref="strategyRef"></TestStrategy>
    </fieldset>
    <!-- 车辆配置 -->
    <fieldset style="margin-top:10px">
      <legend>车辆配置</legend>
      <!-- 测试车辆配置标题 -->
      <div class="editTestFormBoxTableTitle">
        <!-- 测试车辆搜索区域 -->
        <a-row :gutter="[16,0]">
          <a-col
            :xs="24"
            :sm="12"
            :md="8"
            :lg="8"
            :xl="8"
            :xxl="8">
            <a-input @keyup.enter="handleSearch" :placeholder="$t('pleaseInput') + 'VIN'" v-model="testVehicleQuery.vin" />
          </a-col>
          <a-col
            :xs="24"
            :sm="24"
            :md="24"
            :lg="8"
            :xl="8"
            :xxl="8"
            class="btnWarp">
            <a-button type="info" @click="handleSearch" style="margin-right:8px;">
              <i class="iconfont icon-chazhao"></i>
              {{ $t('inquiry') }}
            </a-button>
            <a-button @click="clearCondition">
              <i class="iconfont icon-qingkong"></i>
              {{ $t('clear') }}
            </a-button>
          </a-col>
        </a-row>
      </div>
      <!-- 测试车辆配置列表 -->
      <div style="">
        <s-table v-if="formData.modelId"
                 style="min-height: 350px;"
          ref="table"
          row-key="id"
          :columns="columns"
          :data="getVehicleTbData"
          :scroll="{x:2000,y:1000}"
          :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange,getCheckboxProps:onGetCheckboxProps, type:'radio'}"
          class="h100"
        >
          <template slot="usage" slot-scope="text,record">
            <table-ellipsis v-if="!text && record.status===1" :text="$t('available')"></table-ellipsis>
            <span v-if="record.status===0">不可用</span>
            <span><a v-if="!!text && record.status===1" @click="showUsingTask(record)">{{ $t('inUse') }}</a>{{checkSelect(record)}}</span>
          </template>
          <template slot="ecuVersion" slot-scope="text, record">
            <a @click="showEcuDetail(record)">
              <table-ellipsis :text="'查看'"></table-ellipsis>
            </a>
          </template>
        </s-table>
      </div>
    </fieldset>
    <!-- ECU版本配置 -->
    <fieldset style="margin-top:10px">
      <legend>ECU版本路线配置
        <i class="iconfont icon-wenhao-xianxingyuankuang" @click="showEcuConfigIllustrate"></i>
      </legend>
      <a-row :gutter="40">
        <a-col :md="6" :sm="24">
          <a-form-model-item :label="$t('ECU')" prop="ecuId">
            <ecu-select
              ref="ecuSelectRef"
              :clearOptions="clearEcuOptions"
              :modelIds="formData.modelId"
              v-model="formData.ecuId"
              @changeOption="(val,item)=>{handleEcuChange(val,item)}"
            ></ecu-select>
          </a-form-model-item>
        </a-col>
        <a-col :md="6" :sm="24">
          <a-form-model-item :label="$t('车辆ECU当前版本')">
            <div v-if="selectedRowKeys.length && formData.ecuId">{{ formData.currentVersion }}</div>
          </a-form-model-item>
        </a-col>
      </a-row>
      <loop-test-task-ecu-version-config v-if="formData.ecuId"
        :clearList="formData.modelId"
        :selectedEcuItem="selectedEcuItem"
        :ecuModuleId="formData.ecuId"
        :version-type="versionType"
        :model-id="formData.modelId"
        :time="nowTime"
        :default-versions="defaultSelectedVersions"
        ref="ecuVersionConfigRef">
      </loop-test-task-ecu-version-config>
    </fieldset>
    <!-- 发布说明 -->
    <fieldset style="margin-top:10px">
      <legend>{{ $t('releaseNote') }}</legend>
      <div>
        <a-row>
          <a-col :md="24" :sm="24">
            <!-- 测试说明 -->
            <a-form-model-item :label="$t('测试说明')">
              <custom-text-area
                @change="handlerChange($event)"
                :val="formData.remark"
                :max-len="500"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </div>
    </fieldset>
    <!-- 查看使用中的车辆当前任务列表弹框 -->
    <tasks-in-vehicle-dialog
      @releaseok="refreshData"
      ref="tasksInVehicleDialog"
      v-if="tasksInVehicleQuery"
      :query="tasksInVehicleQuery"></tasks-in-vehicle-dialog>
    <!-- 车辆ecu详情 -->
    <custom-modal
      :width="1100"
      :visible="ecuVersionVisible"
      title="车辆ECU版本详情"
      :destroyOnClose="true"
      class="largeVersionPopup"
      @cancel="handleCancelEcuVersion"
      @full="fullModal"
      modalCls=".largeVersionPopup"
      :isOkBtn="false"
      :bodyStyle="{ height: '500px', overflowY: 'auto' }">
      <car-model-detail-part compt="newLoopUse" :vehicle-id="vehicleId"></car-model-detail-part>
    </custom-modal>
    <!-- 任务ECU配置说明 -->
    <custom-modal
      :width="1100"
      :visible="ecuConfigIllustrateVisible"
      title="任务ECU配置说明"
      :destroyOnClose="true"
      class="largeVersionPopup"
      @cancel="handleCancelEcuConfigIllustrate"
      @full="fullModal"
      modalCls=".largeVersionPopup"
      :isOkBtn="false"
      :bodyStyle="{ height: '500px', overflowY: 'auto' }">
      <div class="ecuConfigIllustrate">
        <h4>循环测试任务说明：</h4>
        <p>1.售后车辆存在相同ECU在不同车中软件版本（如某ECU已发布软件版本V1.0.V2.0V3.0）不一致的问题，每台车都可能需要升级至最新版本；</p>
        <p>2.ECU发布新的软件版本前，为了验证所有已发布的版本是否可正常升级至当前待发布的新版本，需要通过循环测试任务进行验证；</p>
        <p> 3.一个循环测试任务可设置多次循环测试，每一个循环包含多条测试路线，每一条测试路线可对一个或多个的ECU进行升级或降级验证；</p>
        <p>4.任务终止条件（任意条件触发）：循环次数完成，预约时间过期，策略不满足，某一ECU升级失败</p>
        <h4>任务ECU配置说明：</h4>
        <p>1.新增测 线，自动生成路线序号，后续执行按路线序号执行（从小到大）；</p>
        <p>2.选择待测试</p>
        <p class="p2">2.1首条路线选择 CU后，将自动选择源版本（即车辆当前ECU版本）；</p>
        <p class="p2">2.2同一路线中，点击ECU所在行的【操作（ECU)】列 + 按钮时，将在当前ECU的下一行，并可选择待测ECU，同理若当前为首条路线时也将选择源版本 车辆当前ECU版本）；</p>
        <p>3.路线中移除ECU，点击某一ECU所在行的【操作（ECU）】列 - 按钮时，将从路线中移除该ECU ；</p>
        <h4>ECU版本配置示例：</h4>
        <p>版本配置参考：</p>
        <img src="~@assets/ecuConfigProcess.png" alt="示例" style="width: 100%;">
      </div>
    </custom-modal>
</a-form-model>
</template>
<script>
import QuestionMarkTip from '@/views/components/QuestionMarkTip'
import CarModelSelect from '@/views/components/CarModelSelect'
import { checkTextLen,checkVersionName } from '@/utils/validate'
import TestStrategy from '@/views/strategy/FotaUpdate/components/TestStrategy.vue'
import { VehicleConfigListColumns } from '@/views/task/test/list'
import LoopTestTaskEcuVersionConfig from '@/views/task/components/LoopTestTaskEcuVersionConfig.vue'
import CustomTextArea from '@/components/CustomTextArea/index.vue'
import moment from 'moment'
import TasksInVehicleDialog from '@/views/components/TasksInVehicle/dialog.vue'
import CarModelDetailPart from '@/views/vehicle/components/CarModelDetailPart'
import CustomModal from '@/components/CustomModal/index.vue'
import TableEllipsis from '@/components/Ellipsis/TableEllipsis'
import lodash from 'lodash'
import EcuSelect from '@/views/components/EcuSelect.vue'

export default {
  components: {
    QuestionMarkTip,
    CarModelSelect,
    TestStrategy,
    LoopTestTaskEcuVersionConfig,
    CustomTextArea,
    TasksInVehicleDialog,
    CarModelDetailPart,
    CustomModal,
    TableEllipsis,
    EcuSelect
  },
  props: {
    time: {
      type: Number,
      default: 123
    },
    copyId: {
      type: String,
      default: ''
    },
    testType: {
      type: String,
      default: ''
    },
    taskInfo:{
      type: Object,
      default () {
        return {}
      }
    }
  },
  created () {
    this.$set(this.formData, 'code', moment(new Date().getTime()).format('YYYYMMDDHHmmss'))
    // 进入页面，自动生成测试域版本号
    this.initTestVehicleVersion()
    if(this.taskInfo.id){
      this.initTaskData()
    }
  },
  computed: {
    slienceUpgradeType () {
      return this.$store.state.task.slienceUpgradeType
    },
    forceUpgradeType () {
      return this.$store.state.task.forceUpgradeType
    },
    showEcuCurrentVersion () {
      let selectedVehicleId = this.selectedRowKeys
      let ecuId = this.formData.ecuId
      return { selectedVehicleId, ecuId }
    }
  },
  watch: {
    showEcuCurrentVersion:{
      handler(value){
        if( value.selectedVehicleId.length && value.ecuId ){
          let vm=this
          this.$api.getEcuVersion({ vehicleId: value.selectedVehicleId, ecuModuleId: value.ecuId}).then(res=>{
            vm.$nextTick(()=>{
              vm.$set(vm.formData,'currentVersion',res.data && res.data.version || '')
            })
          })
        }
      },
      immediate: true
    },
    'formData.versionName': {
      handler (val) {
        if (val) {
          this.formData.name = `${this.testType}_${this.code}_${this.formData.versionName}`
        }
      }
    },
    'formData.modelId': {
      handler (val) {
        // this.stratetySelectQuery = {
        //   type: 1,
        //   modelId: val,
        //   excludeVehicleVersionId: '-1'
        // }
        // this.formData.circleStrategyId=undefined
        this.nowTime = Date.now()
        if(val){
          this.clearEcuOptions=false
        }else{
          this.clearEcuOptions=true
          this.$refs.ecuSelectRef.options=[]
        }
      }
    },
  },
  data () {
    return {
      ecuConfigIllustrateVisible: false,
      clearEcuOptions:true,
      selectedEcuItem:{},
      vehicleId: '',
      ecuVersionVisible: false,
      tasksInVehicleQuery: null,
      // 默认已选中的零件配置
      defaultSelectedVersions: null,
      versionType: 'TEST',
      moment,
      // 车型代码 用于拼接升级任务名称
      code: '',
      columns: VehicleConfigListColumns,
      // 测试车辆搜索条件
      testVehicleQuery: {
        vin: '',
        vehicleType: 2,
        modelIds: []
      },
      // 已选中的表格行keys
      selectedRowKeys: [],
      // 条件策略id
      conditionStrategyId: '',
      nowTime: Date.now(),
      upgradeTriggerType: 'AUTO',
      // 任务终止条件
      checkUpgradeFailed: true,
      checkCreatedBy: true,
      formData: {
        bookingUpgradeTime: [],
        // 任务名称
        name: undefined,
        modelId: undefined,
        // ecu升级类型
        ecuUpdateType: 4,
        // 是否静默升级
        silenceUpgrade: false,
        // 是否强制升级
        forceUpgrade: undefined,
        // 循环次数
        loopCount: '100',
        // 预约开始
        startTime: '',
        // 预约结束
        endTime: '',
        // 测试说明
        remark: '',
        // 智驾域版本号
        versionName: '',
        // 版本编号
        code: '',
        vehicleVersions:{
          name:undefined
        }
      },
      rules: {
        modelId: [{ required: true, message: this.$t('pleaseSelect') }],
        name: [
          { required: true, message: this.$t('pleaseInput') },
          { validator: checkTextLen() }
        ],
        type: [{ required: true, message: this.$t('pleaseSelect')  }],
        silenceUpgrade: [{ required: true, message: this.$t('pleaseSelect') }],
        forceUpgrade: [{ required: true, message: this.$t('pleaseSelect') }],
        ecuUpdateType: [{ required: true, message: this.$t('pleaseSelect') }],
        loopCount: [{ required: true, message: this.$t('pleaseSelect') }],
        bookingUpgradeTime: [{ required: true, message: this.$t('pleaseSelect')}],
        ecuId:[{ required: true, message: this.$t('pleaseSelect') }]
      }
    }
  },
  methods: {
    changeTime(dates){
      if(moment(dates[1]).diff(moment(dates[0]), 'seconds')>7*24*60*60){
        this.$message.warning('预约时间段不超过7x24小时')
        this.formData.bookingUpgradeTime=[]
      }
    },
    confirmDates(dates){
      if(moment(dates[1]).diff(moment(dates[0]), 'seconds')==0){
        this.$message.warning('预约升级时间的开始时间要小于结束时间 ')
        this.formData.bookingUpgradeTime=[]
      }
    },
    checkSelect(record){
      if(this.selectedRowKeys.includes(record.id)&&(record.taskOccupied || record.status === 0 )){
        this.selectedRowKeys=[]
      }
    },
    initTaskData(){
      const data = this.taskInfo
      // this.$api.getLoopTestTaskDetails(data.id).then(res=>{
      //   const result = res.data
      // })
      this.conditionStrategyId = data.conditionId
      this.formData.modelId = data.modelId
      this.formData.forceUpgrade = data.forceUpgrade
      this.formData.silenceUpgrade = data.silenceUpgrade
      this.formData.loopCount = data.loopCount
      this.upgradeTriggerType = data.type
      this.formData.ecuUpdateType = 4
      this.formData.remark = data.remark
      this.code = data.model.code
      this.selectedRowKeys.push(data.vehicleId)
      this.nowTime=Date.now()
    },
    handleEcuChange(val,item){
      this.selectedEcuItem=item
    },
    fullModal () {
      this.$refs.ecuVersionList.resize()
    },
    // 关闭车辆列表ECU详情
    handleCancelEcuVersion () {
      this.ecuVersionVisible = false
    },
    // 打开车辆列表ECU详情
    showEcuDetail (record) {
      this.ecuVersionVisible = true
      this.vehicleId = record.id
    },
    // 关闭任务ECU配置说明
    handleCancelEcuConfigIllustrate () {
      this.ecuConfigIllustrateVisible = false
    },
    // 打开任务ECU配置说明
    showEcuConfigIllustrate () {
      this.ecuConfigIllustrateVisible = true
    },
    // 查看当前车辆正在执行的任务列表
    showUsingTask (record) {
      console.log(record, 'record')
      this.tasksInVehicleQuery = {
        vehicleId: record.id
      }
      this.$nextTick(() => {
        this.$refs.tasksInVehicleDialog.toggleVisible(true)
      })
    },
    disabledDate (current) {
      return current < moment().subtract(1,"days").endOf('day')
    },
    range(start, end){
      const result = [];
      for (let i = start; i < end; i++) {
          result.push(i);
      }
      return result;
    },
    disabledEndTime(date,type){
      let currentDay = moment().date();    //当下的时间
      let currentHours = moment().hours();
      let currentMinutes = moment().minutes(); 
      if(type=='start' && date){
        let settingHours = moment(date[0]).hours();
        let settingDay = moment(date[0]).date();
        if (date[0] && settingDay === currentDay && settingHours === currentHours) {
          return {       
            disabledHours: () => this.range(0, currentHours),         //设置为当天现在这小时，禁用该小时，该分钟之前的时间
            disabledMinutes: () => this.range(0, currentMinutes),
          };
        }else if (date[0] && settingDay === currentDay && settingHours > currentHours) {
            return { 
                disabledHours: () => this.range(0, currentHours),      //设置为当天现在这小时之后，只禁用当天该小时之前的时间 
                disabledMinutes: () => [],
            };   
        }else if (date[0] && settingDay === currentDay && settingHours < currentHours) {
            return {
                disabledHours: () => this.range(0, currentHours),      //若先设置了的小时小于当前的，再设置日期为当天，需要禁用当天现在这小时之前的时间和所有的分
                disabledMinutes: () => this.range(0, 59),
            }
        }else if (date[0] && settingDay > currentDay) {
            return {                                    
                disabledHours: () => [],                     //设置为当天之后的日期，则不应有任何时间分钟的限制
                disabledMinutes: () => [],
            }
        }
      }else if(type=='end' && date){ 
        let settingHours = moment(date[1]).hours();
        let settingDay = moment(date[1]).date();
        if (date[1] && settingDay === currentDay && settingHours === currentHours) {
          return {       
            disabledHours: () => this.range(0, currentHours),         //设置为当天现在这小时，禁用该小时，该分钟之前的时间
            disabledMinutes: () => this.range(0, currentMinutes),
          };
        }else if (date[1] && settingDay === currentDay && settingHours > currentHours) {
            return { 
                disabledHours: () => this.range(0, currentHours),      //设置为当天现在这小时之后，只禁用当天该小时之前的时间
                disabledMinutes: () => [],
            };   
        }else if (date[1] && settingDay === currentDay && settingHours < currentHours) {
            return {
                disabledHours: () => this.range(0, currentHours),      //若先设置了的小时小于当前的，再设置日期为当天，需要禁用当天现在这小时之前的时间和所有的分
                disabledMinutes: () => this.range(0, 59),
            }
        }else if (date[1] && settingDay > currentDay) {
            return {                                    
                disabledHours: () => [],                     //设置为当天之后的日期，则不应有任何时间分钟的限制
                disabledMinutes: () => [],
            }
        }
      }
    },
    // 调用后台接口，生成最新的测试域版本号
    initTestVehicleVersion () {
      this.$api.getNextVehicleVersion().then(res => {
        if (res.code == 0) {
          this.formData.versionName = res.data
          console.log(res.data, 'res.data')
        }
      })
    },
    // 测试说明
    handlerChange (val) {
      this.formData.remark = val
    },
    // 车型下拉框方法
    changeModelBefore (val, item) {
      if(this.selectedRowKeys.length == 0 && !this.formData.ecuId){
        this.changeModel(val, item)
        return
      }
      const _this = this
      this.$confirm({
        title: _this.$t('systemTip'),
        content: '更换车型后，ECU选项、任务车辆、任务ECU升级配置项将清空，是否确认更换？',
        onOk () {
          _this.testVehicleQuery.vin=''
          _this.changeModel(val,item)
          _this.selectedRowKeys.length = []
          _this.$set(_this.formData,'ecuId',undefined)
        },
        onCancel () {}
      })
    },
    changeModel (val, item) {
      this.formData.modelId = val
      if (item) {
        this.code = item.code
        this.formData.name = `${this.testType}_${item.code}_${this.formData.versionName}`
      }
      this.$nextTick(() => {
        this.$refs.formComp.validateField('modelId')
        this.$refs.formComp.validateField('name')
      })
      this.testVehicleQuery.modelIds = [val]
      this.refreshData()
      this.nowTime = Date.now()
    },
    getVehicleTbData (parameter) {
      const query = {
        ...parameter,
        // modelIds:[this.formData.modelId],
        // modelIds: [this.editRecord.modelId],
        ...this.testVehicleQuery
      }
      if (this.formData.modelId) {
        this.testVehicleQuery.modelIds = [this.formData.modelId]
        query.modelIds = [this.formData.modelId]
      } else {
        return
      }
      return this.$store.dispatch('getVehiclePageData', query)
    },
    refreshData (isToFirstPage = true) {
      if (!this.$refs.table) {
        return
      }
      let obj = null
      if (isToFirstPage) {
        obj = { current: 1 }
      }
      this.$refs.table.loadData(obj)
    },
    // 测试车辆搜索
    handleSearch () {
      this.refreshData()
    },
    clearCondition () {
      this.selectedRowKeys = []
      this.testVehicleQuery.vin = ''
      this.refreshData()
    },
    onGetCheckboxProps: record => ({
      // taskOccupied任务占用中不可使用
      props: {
        disabled: record.taskOccupied || record.status === 0
      }
    }),
    onSelectChange (selectedRowKeys,selectedRows) {
      this.selectedRowKeys = selectedRowKeys
    },
    getPopupContainer () {
      return document.body
    },
    otherCheck () {
      if (this.selectedRowKeys.length === 0) {
        this.$message.error(this.$t('pleaseSelect') + '车辆配置')
        return false
      }
      return true
    },
    openNotification(old, newOne) {
      const key = `open${Date.now()}`;
      this.$notification.open({
        message: '提示',
        description:
          '智驾域版本号'+old+'已过期, 系统自动重新生成' + newOne,
        btn: h => {
          return h(
            'a-button',
            {
              props: {
                type: 'primary',
                size: 'small',
              },
              on: {
                click: () => this.$notification.close(key),
              },
            },
            '确认',
          );
        },
        key
      });
    },
    getFormData () {
      if(!this.$refs.strategyRef.toQualityFormData().items.length){
        reject()
        return
      }
      return new Promise((resolve, reject) => {
        this.$refs.formComp.validate(valid => {
          if(!valid){
            this.$nextTick(() => {
              let isError = document.getElementsByClassName('ant-form-item-control has-error')
              isError[0].scrollIntoView({
                // 滚动到指定节点
                // 值有start,center,end，nearest，当前显示在视图区域中间
                block: 'center',
                // 值有auto、instant,smooth，缓动动画（当前是慢速的）
                behavior: 'smooth',
              })
            })
            reject(valid)
            return
          }
          if (!this.otherCheck()) {
            reject(new Error('未选择车辆'))
            return
          }
          let configData = this.$refs.ecuVersionConfigRef.getECUConfigData()
          if (!configData.length) {
            reject(new Error('请添加ECU版本配置项'))
            this.$message.error('请添加ECU版本配置项')
            return
          }else if(configData.length<=1){
            reject(new Error('ECU版本配置项最少需要两项'))
            this.$message.error('ECU版本配置项最少需要两项')
            return
          }
          const data = lodash.clone(this.formData)
          data.type = this.upgradeTriggerType
          data.startTime=this.formData.bookingUpgradeTime[0].format('YYYY-MM-DD HH:mm:ss')
          data.endTime=this.formData.bookingUpgradeTime[1].format('YYYY-MM-DD HH:mm:ss')
          data.vehicleIds = [...this.selectedRowKeys]
          data.items=this.$refs.strategyRef.toQualityFormData().items
          // 判断智驾域版本号是否已存在
          this.$api.getNextVehicleVersion().then(res=>{
            if(res.code == 0){
              console.info(res.data)
              const old = this.formData.versionName
              // 因为测试智驾域版本号是自动生成的，在提交前进行再次获取最新
              this.formData.versionName = res.data
              const newOne = this.formData.versionName
              if(old != newOne){
                this.$refs.ecuVersionConfigRef.updateVersionName(this.formData.versionName)
                this.openNotification(old, newOne)
                return
              }
              // 处理ecu版本路线配置数据
              let formatConfigData=[]
              configData.forEach(item=>{
                formatConfigData.push({
                  name:item.smartDrivingDomainVersion,
                  ecuVersions:[item]
                })
              })
              data.vehicleVersions=formatConfigData
              // console.log('@@@@@data',data)
              resolve(data);
            }else{
              reject(new Error('无法查询最新可用版本号'))
              return
            }
          })
        })
      })
    }
  }
}
</script>
<style scoped lang="less">
  .editTestFormBoxTableTitle {
    flex:none;
    margin-bottom: 16px;
  }
fieldset
{
  border: 1px solid #ccc;
  padding: 8px;
  legend{
    width:auto;
    border-bottom: none;
    color: blue;
    background-color: #FFFFFF;
    font-size: 14px;
    margin-bottom:0px
  }
}
.ecuConfigIllustrate {
  h4 {
    margin-bottom: 10px;
    font-weight:bold;
  }
  p {
    margin-bottom: 10px;
    text-indent: 16px;
  }
  .p2 {
    margin-bottom: 10px;
    text-indent: 32px;
  }
}
</style>
